import "bootstrap-datepicker";
import { InputComponent } from './inputcomponent.js';
import { DateComponent } from './datecomponent.js';
import { Component } from '/src/components/component/component.js';

export class SearchBarComponent extends Component {
    constructor(container, options = {}) {
        super(container, options);
        this.configItems = options.config && options.config !== '' && !(typeof options.config === 'object')
            ? [...new Set(options.config.split(',').filter(Boolean))]
            : [];
        this.components = new Map(); // 保存所有子组件实例
        this.initialized = false;
    }

    async init() {
        await this.render();
        this.bindEvents();
        this.initialized = true;
    }

    async render() {
        this.container.empty();
        this.components.clear();

        const componentPromises = this.configItems.map(item => this.createComponent(item));
        await Promise.all(componentPromises);
    }

    async createComponent(item) {
        const parts = item.split('-');
        const [type, ...params] = parts;

        const componentFactory = {
            date: () => new DateComponent(this.container, { type: 'day' }),
            input: () => new InputComponent(this.container, {
                fieldName: params[0],
                name: params[1]
            })
        };

        const factory = componentFactory[type];
        if (!factory) {
            throw new Error(`不支持的组件类型: ${type}`);
        }

        const component = factory();
        const componentId = `${type}_${component.cid}`;

        this.components.set(componentId, component);
        await component.init();

        return component;
    }

    bindEvents() {
        // 你可以在这里监听子组件的事件
        this.components.forEach(comp => {
            comp.on('typeChange', (type) => {
                // 可以触发 SearchBar 的事件
                this.trigger('dateTypeChange', type);
            });
        });
    }

    async addComponent(item) {
        const parts = item.split('-');

        let component = null;

        switch (parts[0]) {
            case 'input':
                // 检查是否已存在
                const exists = this.components.some(comp =>
                    comp instanceof InputComponent && comp.fieldName === parts[1]
                );
                if (exists) {
                    console.warn(`addComponent: 已存在 id 为 '${parts[1]}' 的输入框`);
                    return null;
                }

                component = new InputComponent(this.container, {
                    fieldName: parts[1],
                    name: parts[2]
                });
                break;

            case 'date':
                // options 可以包含 type: 'day', 'month', 'year'
                const dateType = 'day';

                // 检查是否已存在 date 组件
                const dateExists = this.components.some(comp => comp instanceof DateComponent);
                if (dateExists) {
                    console.warn('addComponent: 已存在日期组件，不允许多个');
                    return null;
                }

                component = new DateComponent(this.container, { type: dateType });
                break;

            default:
                console.error(`addComponent: 不支持的组件类型 '${type}'`);
                return null;
        }

        // 通用逻辑
        this.components.push(component);
        this.configItems.push(item);
        await component.init();
        this.bindEvents(); // 重新绑定事件

        return component;
    }

    /**
     * 获取所有搜索数据
     * @returns {Object}
     */
    getSearchData() {
        if (!this.initialized || this.components.length === 0) {
            return {};
        }

        const data = {};
        this.components.forEach(comp => {
            if (comp instanceof InputComponent) {
                data[comp.fieldName] = comp.getValue();
            } else if (comp instanceof DateComponent) {
                const range = comp.getDate();
                data.beginDate = range.beginDate;
                data.endDate = range.endDate;
                data.dateType = range.type;
            }
        });
        return data;
    }

    getSearchConfigData() {
        return this.configItems.join(',');
    }

    /**
     * 重置所有输入
     */
    reset() {
        this.components.forEach(comp => comp.clear());
    }

    /**
     * 清空所有输入（clear 是 reset 的别名）
     */
    clear() {
        this.reset();
    }

    destroy() {
        // 销毁所有子组件
        this.components.forEach(comp => {
            if (comp.destroy && typeof comp.destroy === 'function') {
                comp.destroy();
            }
        });

        this.components.clear();
        this.configItems = [];
        this.initialized = false;

        super.destroy();
    }
}